import { defineComponent, reactive, ref } from 'vue'
import { Form, Input, Button, Row, Col, message } from 'ant-design-vue'
import '@/views/index.scss'
import { register, sendEmailCode } from '@/api/sys/user'
import { useRouter } from 'vue-router'

export interface userInfo {
  loginEmail: string
  password: string
  confirmPassword: string
  code: number
}

export default defineComponent({
  name: 'register',
  setup() {
    const router = useRouter()
    const ruleForm = ref<any>(null)
    const codeUs = reactive({
      codeText: '获取验证码',
      numTime: 60,
      codeState: false,
      clonkInterval: 0
    })

    const data = reactive({
      labelCol: { span: 5 },
      wrapperCol: { span: 15 }
    })

    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 16,
          offset: 8,
        },
      },
    }

    const modelRef = reactive({
      loginEmail: '',
      password: '',
      confirmPassword: '',
      code: ''
    })

    const validatePass = async (rule: any, value: string | number) => {
      if (value === '') {
        return Promise.reject('请输入密码')
      } else {
        if (modelRef.confirmPassword !== '') {
          ruleForm.value.validateField('confirmPassword')
        }
        return Promise.resolve()
      }
    }

    const validatePass2 = async (rule: any, value: string | number) => {
      if (value === '') {
        return Promise.reject('请输入确认密码')
      } else if (value !== modelRef.password) {
        return Promise.reject('两次密码不一致')
      } else {
        return Promise.resolve()
      }
    }

    const rulesRef = reactive({
      loginEmail: [
        { required: true, message: '请输入登录邮箱', trigger: 'blur' },
        { message: '请输入正确的邮箱', type: 'email', trigger: 'blur' }
      ],
      password: [
        { required: true, validator: validatePass, trigger: 'change' }
      ],
      confirmPassword: [
        { required: true, validator: validatePass2, trigger: 'change' }
      ],
      code: [
        { required: true, message: '请输入验证码', trigger: 'blur' }
      ]
    })

    // 倒计时函数
    const countdown = () => {
      codeUs.numTime--
      if (codeUs.numTime > 0) {
        codeUs.codeText = codeUs.numTime + '秒后可重新获取'
      } else {
        clearInterval(codeUs.clonkInterval)
        codeUs.codeText = '获取验证码'
        codeUs.codeState = false
        codeUs.numTime = 60
      }
    }

    // 获取验证码
    const getCode = () => {
      ruleForm.value.validate('loginEmail').then(async (res: any) => {
        const codeResult = await sendEmailCode({ loginEmail: modelRef.loginEmail })
        if (codeResult.success) {
          codeUs.codeState = true
          codeUs.codeText = codeUs.numTime + '秒后可重新获取'
          codeUs.clonkInterval = setInterval(countdown, 1000)
        } else {
          message.error(codeResult.msg)
        }
      }).catch((error: any) => {
        console.log(error, 3)
      })
    }

    // 所有验证都通过的情况走这里，相当于提交
    const onFinish = async (userInfo: userInfo) => {
      const result = await register(userInfo)
      if (result.success) {
        message.success(result.msg)
        await router.push('login')
      } else {
        message.error(result.msg)
      }
    }

    return () => (
      <div class='register-form'>
        <Form
          ref={ruleForm}
          name="control-ref"
          labelCol={data.labelCol}
          wrapperCol={data.wrapperCol}
          model={modelRef}
          rules={rulesRef}
          onFinish={onFinish}
        >
          <Form.Item
            name="loginEmail"
            label="邮箱"
            hasFeedback
          >
            <Input v-model={[modelRef.loginEmail, 'value']} type="email" placeholder='请输入邮箱'/>
          </Form.Item>
          <Form.Item
            name="password"
            label="密码"
            hasFeedback
          >
            <Input.Password v-model={[modelRef.password, 'value']} type="password" placeholder='请输入密码'/>
          </Form.Item>
          <Form.Item
            name='confirmPassword'
            label="确认密码"
            hasFeedback
          >
            <Input.Password v-model={[modelRef.confirmPassword, 'value']} type="password" placeholder='请输入确认密码'/>
          </Form.Item>
          <Form.Item label="验证码">
            <Row>
              <Col span={12}>
                <Form.Item
                  name="code"
                  hasFeedback
                >
                  <Input v-model={[modelRef.code, 'value']} placeholder='请输入验证码'/>
                </Form.Item>
              </Col>
              <Col span={12}>
                <Button onClick={getCode} disabled={codeUs.codeState}>{codeUs.codeText}</Button>
              </Col>
            </Row>
          </Form.Item>
          <Form.Item {...tailFormItemLayout}>
            <Button type="primary" htmlType="submit">
              注册
            </Button>
          </Form.Item>
        </Form>
      </div>
    )
  }
})
